package com.ruoyi.framework.security.service;

import javax.annotation.Resource;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserGetbyunionidRequest;
import com.dingtalk.api.response.OapiUserGetbyunionidResponse;
import com.ruoyi.project.erp.service.IDingTalkService;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.tool.SmsUtil;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.BlackListException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserNotExistsException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysConfigService;
import com.ruoyi.project.system.service.ISysUserService;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
@Slf4j
@Service
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IDingTalkService dingTalkService;

    @Autowired
    private PermissionService permissionService;
    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;
    private final static String APP_AUTH_CODE = "APP_AUTH_CODE";

    private final static String APP_AUTH_PHONE_COUNT = "APP_AUTH_PHONE_COUNT";
    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String phonenumber, String password, String code, String uuid)
    {
        // 验证码校验
        // 登录前置校验
        loginPreCheck(phonenumber, password);
        // 用户验证
        Authentication authentication = null;
        // 1. 使用传入的 phonenumber 去数据库查询用户
        SysUser user = userMapper.selectUserByPhonenumber(phonenumber);

        // 2. 如果根据手机号找不到用户，直接抛出密码不匹配的异常，防止泄露用户信息
        if (user == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phonenumber, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }

        // 3. 获取到该用户的真实用户名
        String actualUsername = user.getUserName();

        // ======================= 修改结束 =======================

        try
        {
            // 注意：这里传给 Spring Security 的是 actualUsername，而不是前端传来的手机号
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(actualUsername, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername，此时传递的是正确的用户名
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                // 日志记录使用手机号和真实用户名，方便排查问题
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(actualUsername + "(" + phonenumber + ")", Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(actualUsername + "(" + phonenumber + ")", Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }

        // 后续逻辑保持不变
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(actualUsername, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // recordLoginInfo(loginUser.getUserId()); // RuoYi-Vue-Plus版本可能有此方法
        // 生成token
        return tokenService.createToken(loginUser);
    }










    public String login(String username,String code)
    {

        String password = "admin123";
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }


    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            redisCache.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    public void sendCode(String phone) throws Exception {
        // key建议抽成常量
        String codeKey = APP_AUTH_CODE + phone;
        log.info("开始执行发送验证码！！！！！！！！！！！！！！！！手机号是："+phone);
        // 获取旧码，如果存在就复用
        String code = redisCache.getCacheObject(codeKey);
        if (code == null) {
            code = GenerateCode(6);
            redisCache.setCacheObject(codeKey, code, 5, TimeUnit.MINUTES);
        } // 注意: 只生成和存一次
        log.info("随机生成验证码是："+code);
        Integer count = redisCache.getCacheObject(APP_AUTH_PHONE_COUNT + phone);
        if (count == null) {
            count = 0;
        }
        if (count != null && count >= 10) {
            throw new RuntimeException("获取验证码频繁，请稍后重试。");
        }
//        sendCode.sendCodeToPhone(phone, code);
        String sign = "沈阳华拓智联科技有限公司";
        String template = "SMS_489765324";
        String params = "{\"code\":\"" + code + "\"}";
        log.info("短信体："+params);
        SendSmsResponse resp = SmsUtil.sendSms(phone, sign, template, params);
        log.info("发送短信回执："+resp);
        System.out.println(resp.getBody().getCode()); // 判断OK即为成功
        redisCache.setCacheObject(codeKey, code, 5,TimeUnit.MINUTES);
    }

    public static String GenerateCode(int length){
        String code = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int r = random.nextInt(10); //每次随机出一个数字（0-9）
            code = code + r;  //把每次随机出的数字拼在一起
        }
        return code;
    }

    public String loginDingTalk(String unionId) throws Exception {
        String accessToken = dingTalkService.getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid");
        OapiUserGetbyunionidRequest req = new OapiUserGetbyunionidRequest();
        req.setUnionid(unionId);
        OapiUserGetbyunionidResponse rsp = client.execute(req, accessToken);
        SysUser user = userMapper.selectUserByDdUserId(rsp.getResult().getUserid());
        String username = user.getUserName();
        String password = "1q2w3e$R";
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public String loginByPhone(SysUser user) {
        // 因为 user 是已经验证过的，所以我们在这里直接构建 LoginUser
        LoginUser loginUser = createLoginUser(user);

        // 记录日志、更新登录信息...
        recordLoginInfo(loginUser.getUserId());
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, "手机号登录成功"));

        // 直接生成并返回 Token，完全绕过了 AuthenticationManager
        return tokenService.createToken(loginUser);
    }
    /**
     * 辅助方法：根据 SysUser 对象创建 LoginUser 对象
     * 这个方法的核心逻辑，是模仿了 UserDetailsServiceImpl 成功加载用户后的构建过程。
     * 我们需要它，是因为在免密登录流程中，我们绕过了 UserDetailsServiceImpl，必须自己完成 LoginUser 的创建。
     *
     * @param user 数据库中查询出的用户信息
     * @return 包含权限信息的 LoginUser 对象
     */
    public LoginUser createLoginUser(SysUser user) {
        // 查看 LoginUser 的构造函数，它通常需要：
        // 1. 用户ID (user.getUserId())
        // 2. 部门ID (user.getDeptId())
        // 3. 用户实体本身 (user)
        // 4. 权限集合 (通过 permissionService 获取)
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }

    public SysUser selectUserByUserName(String userName) {
        return null;
    }

    public int resetUserPwd(String userId, String encryptPassword) {

        SysUser user = userMapper.selectUserByDdUserId(userId);
        user.setPassword(encryptPassword);
        return userMapper.updateUser(user);
    }
}
